package common.test;

import common.TreeNode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 230. 二叉搜索树中第K小的元素
 */
public class _230_KthSmallest {

    public int kthSmallest(TreeNode root, int k) {
        if (root == null || k < 1) {
            return 0;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            TreeNode node = stack.pop();
            if (--k < 1) {
                return node.val;
            }
            root = node.right;
        }
        return 0;
    }
}
